package xyz.bali16.application.interceptor;


import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import xyz.bali16.application.core.utils.AuthUtils;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.service.DataService;
import xyz.bali16.application.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component

public class DataInterceptor implements HandlerInterceptor {
    @Autowired
     DataService dataService;
    @Autowired
     UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 统计UV
        String ip = request.getRemoteHost();

        dataService.recordUV(ip);
        String username = AuthUtils.getCurrentUsername();
        if (username == null) {
            return true;
        }
        User user = userService.getByUsername(username);
        // 统计DAU
        if (user != null) {
            dataService.recordDAU(user.getUserId());
        }

        return true;
    }
}
